import http from '../../../utils/https.js'
Page({
  data: {
    vehicleList:[],
    residentId:'',
    parkingSpace:[],
  },
  onLoad(options){
    // 从本地缓存获取residentId
    const residentId = wx.getStorageSync('residentId');
    console.log('获取到的residentId:', residentId);
    this.setData({
      residentId: residentId
    });
    this.getVehicleList();
  },
  
  // 下拉刷新
  onPullDownRefresh() {
    console.log('触发下拉刷新');
    this.getVehicleList().then(() => {
      wx.stopPullDownRefresh();
      wx.showToast({
        title: '刷新成功',
        icon: 'success',
        duration: 1500
      });
    }).catch(() => {
      wx.stopPullDownRefresh();
      wx.showToast({
        title: '刷新失败',
        icon: 'none',
        duration: 1500
      });
    });
  },
  getVehicleList(){
    // 检查residentId是否存在
    if (!this.data.residentId) {
      wx.showToast({
        title: '用户信息不存在，请重新登录',
        icon: 'none'
      });
      return Promise.reject('用户信息不存在');
    }

    // 从this.data获取residentId并转换为整数类型
    const rid = parseInt(this.data.residentId);
    console.log('转换为整数后的residentId:', rid);
    
    // 验证转换后的ID是否有效
    if (isNaN(rid) || rid <= 0) {
      wx.showToast({
        title: '用户ID无效',
        icon: 'none'
      });
      return Promise.reject('用户ID无效');
    }
    
    // 根据接口要求，直接传递residentId参数
    const params = { residentId: rid };
    console.log('发送请求参数:', params);
    
    return http.get('vehicle/vehicle/list', params).then(res => {
      console.log('获取到的数据', res);
      if (res.code === 200 && res.rows) {
        // 处理图片URL，将相对路径转换为绝对路径
        const processedVehicles = res.rows.map(vehicle => {
          if (vehicle.imageUrl && !vehicle.imageUrl.startsWith('http')) {
            // 如果是相对路径，转换为完整的URL
            vehicle.imageUrl = 'http://localhost:8080' + vehicle.imageUrl;
          }
          // 初始化图片加载状态
          vehicle.imageLoading = true;
          // 确保vehicleStatus字段存在，默认为0（审核通过）
          if (vehicle.vehicleStatus === undefined || vehicle.vehicleStatus === null) {
            vehicle.vehicleStatus = 0;
          }
          return vehicle;
        });
        
        this.setData({
          vehicleList: processedVehicles
        });
        console.log('车辆列表更新成功，共', processedVehicles.length, '条记录');
        
        // 获取车辆列表成功后，为每个车辆查询对应的车位信息
        this.getParkingSpaceForVehicles(processedVehicles);
        return processedVehicles;
      } else {
        wx.showToast({
          title: res.message || '获取车辆列表失败',
          icon: 'none'
        });
        return Promise.reject(res.message || '获取车辆列表失败');
      }
    }).catch(err => {
      console.error('获取车辆列表失败:', err);
      wx.showToast({
        title: '网络请求失败，请检查网络连接',
        icon: 'none'
      });
      return Promise.reject(err);
    });
  },

  // 根据车辆ID查询车位信息
  getParkingSpaceByVehicleId(vehicleId) {
    if (!vehicleId) {
      console.error('车辆ID不能为空');
      return Promise.reject('车辆ID不能为空');
    }

    const params = { vehicleId: vehicleId };
    console.log('查询车位信息，车辆ID:', vehicleId, '参数:', params);

    return http.get('parkingSpace/parkingSpace/list', params).then(res => {
      console.log('车位信息查询结果:', res);
      if (res.code === 200 && res.rows) {
        return res.rows;
      } else {
        console.warn('未找到车辆ID为', vehicleId, '的车位信息');
        return [];
      }
    }).catch(err => {
      console.error('查询车位信息失败，车辆ID:', vehicleId, '错误:', err);
      return [];
    });
  },

  // 为所有车辆查询车位信息
  getParkingSpaceForVehicles(vehicles) {
    if (!vehicles || vehicles.length === 0) {
      console.log('没有车辆信息，跳过车位查询');
      return;
    }

    console.log('开始为', vehicles.length, '辆车查询车位信息');
    
    // 只查询私家车(sort=2)的车位信息
    const privateVehicles = vehicles.filter(vehicle => vehicle.sort === 2);
    console.log('私家车数量:', privateVehicles.length);
    
    if (privateVehicles.length === 0) {
      console.log('没有私家车，跳过车位查询');
      // 直接更新车辆列表，标记车辆类型
      const processedVehicles = vehicles.map(vehicle => ({
        ...vehicle,
        vehicleType: vehicle.sort === 1 ? '月卡车辆' : '私家车',
        parkingSpaces: [],
        // 确保vehicleStatus字段存在
        vehicleStatus: vehicle.vehicleStatus !== undefined && vehicle.vehicleStatus !== null ? vehicle.vehicleStatus : 0
      }));
      
      this.setData({
        vehicleList: processedVehicles
      });
      return;
    }
    
    // 使用Promise.all并发查询私家车的车位信息
    const parkingSpacePromises = privateVehicles.map(vehicle => {
      return this.getParkingSpaceByVehicleId(vehicle.id).then(parkingSpaces => {
        // 将车位信息关联到车辆对象
        return {
          ...vehicle,
          vehicleType: '私家车',
          parkingSpaces: parkingSpaces
        };
      });
    });

    Promise.all(parkingSpacePromises).then(privateVehiclesWithParking => {
      console.log('私家车车位信息查询完成:', privateVehiclesWithParking);
      
      // 处理所有车辆，包括月卡车辆
      const allVehiclesWithInfo = vehicles.map(vehicle => {
        if (vehicle.sort === 1) {
          // 月卡车辆
          return {
            ...vehicle,
            vehicleType: '月卡车辆',
            parkingSpaces: [],
            // 确保vehicleStatus字段存在
            vehicleStatus: vehicle.vehicleStatus !== undefined && vehicle.vehicleStatus !== null ? vehicle.vehicleStatus : 0
          };
        } else if (vehicle.sort === 2) {
          // 私家车，查找对应的车位信息
          const vehicleWithParking = privateVehiclesWithParking.find(v => v.id === vehicle.id);
          return vehicleWithParking || {
            ...vehicle,
            vehicleType: '私家车',
            parkingSpaces: [],
            // 确保vehicleStatus字段存在
            vehicleStatus: vehicle.vehicleStatus !== undefined && vehicle.vehicleStatus !== null ? vehicle.vehicleStatus : 0
          };
        } else {
          // 其他类型车辆
          return {
            ...vehicle,
            vehicleType: '其他',
            parkingSpaces: [],
            // 确保vehicleStatus字段存在
            vehicleStatus: vehicle.vehicleStatus !== undefined && vehicle.vehicleStatus !== null ? vehicle.vehicleStatus : 0
          };
        }
      });
      
      // 更新车辆列表，包含车位信息和车辆类型
      this.setData({
        vehicleList: allVehiclesWithInfo
      });

      // 提取所有车位信息到parkingSpace数组
      const allParkingSpaces = allVehiclesWithInfo.reduce((acc, vehicle) => {
        if (vehicle.parkingSpaces && vehicle.parkingSpaces.length > 0) {
          acc.push(...vehicle.parkingSpaces);
        }
        return acc;
      }, []);

      this.setData({
        parkingSpace: allParkingSpaces
      });

      console.log('车位信息更新完成，共', allParkingSpaces.length, '个车位');
    }).catch(err => {
      console.error('批量查询车位信息失败:', err);
    });
  },

  // 手动刷新车位信息
  refreshParkingSpace() {
    console.log('手动刷新车位信息');
    if (this.data.vehicleList && this.data.vehicleList.length > 0) {
      // 重新获取车辆列表，这样可以确保获取最新的车辆信息和车位信息
      this.getVehicleList();
    } else {
      console.log('没有车辆信息，先获取车辆列表');
      this.getVehicleList();
    }
  },

  // 查询单个车辆的车位信息
  getParkingSpaceForSingleVehicle(vehicleId) {
    console.log('查询单个车辆的车位信息:', vehicleId);
    
    // 查找对应的车辆信息
    const vehicle = this.data.vehicleList.find(v => v.id === vehicleId);
    if (!vehicle) {
      console.error('未找到车辆ID为', vehicleId, '的车辆信息');
      return;
    }
    
    // 只有私家车(sort=2)才需要查询车位信息
    if (vehicle.sort !== 2) {
      console.log('车辆ID', vehicleId, '不是私家车，跳过车位查询');
      return;
    }
    
    this.getParkingSpaceByVehicleId(vehicleId).then(parkingSpaces => {
      console.log('车辆ID', vehicleId, '的车位信息:', parkingSpaces);
      
      // 更新对应车辆的车位信息
      const updatedVehicleList = this.data.vehicleList.map(vehicle => {
        if (vehicle.id === vehicleId) {
          return {
            ...vehicle,
            parkingSpaces: parkingSpaces
          };
        }
        return vehicle;
      });

      this.setData({
        vehicleList: updatedVehicleList
      });

      // 更新总的车位信息数组
      const allParkingSpaces = updatedVehicleList.reduce((acc, vehicle) => {
        if (vehicle.parkingSpaces && vehicle.parkingSpaces.length > 0) {
          acc.push(...vehicle.parkingSpaces);
        }
        return acc;
      }, []);

      this.setData({
        parkingSpace: allParkingSpaces
      });

      console.log('单个车辆车位信息更新完成');
    });
  },

  // 图片加载失败处理
  onImageError(e) {
    const index = e.currentTarget.dataset.index;
    console.log('图片加载失败，索引:', index, '使用默认图片');
    
    // 更新对应车辆的图片为默认图片
    const vehicleList = this.data.vehicleList;
    if (vehicleList[index]) {
      vehicleList[index].imageUrl = '/mine/images/car.png';
      vehicleList[index].imageLoading = false;
      this.setData({
        vehicleList: vehicleList
      });
    }
  },

  // 图片加载成功处理
  onImageLoad(e) {
    const index = e.currentTarget.dataset.index;
    console.log('图片加载成功，索引:', index);
    
    // 更新对应车辆的图片加载状态
    const vehicleList = this.data.vehicleList;
    if (vehicleList[index]) {
      vehicleList[index].imageLoading = false;
      this.setData({
        vehicleList: vehicleList
      });
    }
  },

  goToAddCar:function() {
    wx.navigateTo({
      url: '/mine/pages/add-car/add-car'
    });
  },
  gotoCarDetails:function(e){
    // 获取点击的车辆ID
    const vehicleId = e.currentTarget.dataset.id;
    
    // 验证车辆ID是否存在
    if (!vehicleId) {
      wx.showToast({
        title: '车辆ID无效',
        icon: 'none'
      });
      return;
    }
    
    console.log('点击车辆，ID:', vehicleId, '准备跳转到详情页面');
    
    // 查找对应的车辆信息
    const vehicle = this.data.vehicleList.find(v => v.id == vehicleId);
    if (vehicle) {
      console.log('车辆信息:', vehicle);
    }
    
    // 跳转到车辆详情页面
    wx.navigateTo({
      url: `/mine/pages/car-details/car-details?id=${vehicleId}`,
      success: () => {
        console.log('成功跳转到车辆详情页面，车辆ID:', vehicleId);
      },
      fail: (err) => {
        console.error('跳转车辆详情页面失败:', err);
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  }
});
